# coding=utf-8
import requests, time, re
from queue import Queue
from flask_cors import *
from flask import request, Flask, jsonify

app = Flask(__name__)
# 跨域设置
CORS(app, supports_credentials=True)
app.config['JSON_AS_ASCII'] = False
# mapkeys列表每个key有1w请求 每个账号可以注册5个key https://lbs.qq.com/
MapKeys = [
    # 18201419686
    '2HYBZ-BKSK4-HHCUH-XC6LB-NIX2Z-VIF5J',
    'CTTBZ-6N2KU-7SRVW-BDSJF-IUTRV-LHF4F',
    '23IBZ-G7CKF-KLOJO-NGIML-N7Q56-D4BNG',
    '46UBZ-QDWCF-URKJE-J3CGD-OPRQQ-HFFFE',
    'VNGBZ-U5BK4-7PYUD-X7FM3-2AH2O-INBFG',
    # 18106140097
    'P4RBZ-CBHW2-T6KU3-CJCKC-XFBLS-FABJH',
    'XR3BZ-QIWC4-VPDU7-XGC3A-KIV23-APBOF',
    'RX7BZ-AMP6U-HSJVC-B5U5C-CX5RO-7WB6B',
    'NQZBZ-J4E6U-KWDVF-BT6MQ-J7KOS-KUBED',
    'IIPBZ-LQL6I-UTZGD-523UA-LEGFV-MKFHR',
    # 17611630631
    'ZXMBZ-663K2-E6BUO-C57LP-VTSLS-VSBBR',
    '6CPBZ-BYM66-WQUSM-M4SPU-UMAPZ-YYFH3',
    'YOKBZ-WOBWJ-3UMFG-F722B-3P2Y5-WTBVW',
    'XLHBZ-27AKJ-DB5FY-FWHUB-3XE3J-3OFKT',
    'NU7BZ-ODHCQ-JCF5C-GCKBT-DLSDH-IDBIS',
    # 13301499615
    'MMSBZ-TTYK2-P6CUZ-CFP2U-Q4BL5-F2FHH',
    'QSVBZ-KP3CW-F3NRD-OMDC7-QP5U3-3YF5S',
    'MEUBZ-X22KJ-527FK-FB7DU-BP235-OVBEV',
    '6MCBZ-2AICQ-QNX5T-GJX5N-7ASXV-PNFJW',
    '64JBZ-JRP6I-C77GG-5GGNE-XWEFS-AFFLJ',
]

KeysQueue = Queue()
[KeysQueue.put(MapKey) for MapKey in MapKeys]


@app.route('/', methods=['GET'])
def index():
    address = request.args.get('address')
    if address is None:
        return '''
            <!DOCTYPE html>
            <html lang="zh-CN">
            <head>
                <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
                <title>省市区/县市三级解析</title>
                <style type="text/css">
                    body {width: 700px;margin: 40px auto;border: 1px solid #999;padding: 0 20px;border-radius: 10px;}
                    li {list-style: none;}
                    h2 {text-align: center;}
                </style>
            </head>
            <body>
            <h2>省市区/县市三级解析</h2>
            <ul>
                <li>1、接口地址:<a href="./?address=海淀区西北旺东路联想总部西区">http://127.0.0.1:8080?address=地址</a></li>
                <li>2、上传参数:采用get提交参数，参数为address</li>
                <li>3、错误代码:10200为数据正常返回,10500为服务器内部错误,可以二次请求</li>
                <li>4、返回数据:info为需求数据,格式为列表,列表包含三个元素</li>
            </ul>
            <p>该api仅供爬虫爱好者学习与娱乐，如有侵权或者技术疑问,请发邮件至<strong>chinapython@yeah.net</strong>！</p>
            </body>
            </html>
            '''
    if len(address) <= 1:
        return jsonify({
            'code': 10200,
            'msg': '地址过短',
            'info': ['', '', ''],
        })
    times = 0
    while KeysQueue.empty():
        times += 1
        time.sleep(1)
        if times > 5:
            return jsonify({
                'code': 10500,
                'msg': '无法获取key',
                'info': [],
            })
    key = KeysQueue.get()
    if key is None:
        return jsonify({
            'code': 10500,
            'msg': 'key值为None',
            'info': [],
        })
    KeysQueue.put(key)
    url = 'https://apis.map.qq.com/ws/geocoder/v1/?address={}&key={}'.format(address, key)
    try:
        response = str(requests.get(url).text).replace('\n', '').replace(' ', '')
        item = re.findall('"province":"(.*?)","city":"(.*?)","district":"(.*?)"', response)
        info = ['', '', ''] if len(item) == 0 else list(item[0])
    except:
        info = ['', '', '']
    return jsonify({
        'code': 10200,
        'msg': '数据返回正常',
        'info': info,
    })


if __name__ == '__main__':
    app.run(
        host='127.0.0.1',
        port=8081,
        debug=True
    )
